<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>编辑用户</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <h2>编辑用户</h2>
    <form id="edit-user-form">
        <input type="text" id="username" placeholder="用户名" required>
        <input type="password" id="password" placeholder="密码" required>
        <button type="submit">保存修改</button>
    </form>

    <script>
        const urlParams = new URLSearchParams(window.location.search);
        const userId = urlParams.get('id');

        // 获取用户信息
        fetch(`http://localhost:3002/users/${userId}`, {
            method: 'GET',
            credentials: 'same-origin'  // 发送会话 Cookie
        })
        .then(response => response.json())
        .then(data => {
            if (data.username) {
                document.getElementById('username').value = data.username;
            } else {
                alert(data.message || '无法获取用户数据');
            }
        })
        .catch(err => {
            console.error('获取用户数据失败:', err);
        });

        document.getElementById('edit-user-form').addEventListener('submit', function (event) {
            event.preventDefault();  // 阻止表单的默认提交行为

            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;

            // 发送更新请求到后端
            fetch(`http://localhost:3002/users/${userId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ username, password }),
                credentials: 'same-origin'  // 发送会话 Cookie
            })
            .then(response => response.json())
            .then(data => {
                if (data.message === '用户更新成功') {
                    alert('用户更新成功');
                    window.location.href = 'admin.html';  // 更新成功后跳转到管理页面
                } else {
                    alert(data.message);
                }
            })
            .catch(err => {
                console.error('更新用户失败:', err);
            });
        });
    </script>
    <footer>
        <p>项目由 张成飞制作 | 版权所有</p>
    </footer>
</body>
</html>

